package com.shujia.uerService;

import com.shujia.Dao.StuentDao;
import com.shujia.JdbcUtil.RedisUtil;
import com.shujia.user.Student;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

public class StudentService_plus {
        private StuentDao stuentDao = new StuentDao();

        public Student QueryStudentById (String id) {
            String key = "Student_cache" + id;

            Jedis jedis = null;
            try {
                Student student = new Student();
                jedis = RedisUtil.getConnction();
                Map<String, String> map = jedis.hgetAll(key);
                if (map != null && !map.isEmpty()) {
                    student.setId(id);
                    student.setName(map.get("name"));
                    student.setAge(Integer.parseInt(map.get("age")));
                    student.setGender(map.get("gender"));
                    student.setClazz(map.get("clazz"));

                    jedis.expire(key, 10);
                    return student;
                }
            } catch (Exception e) {
                System.out.println("读取缓存失败");
            } finally {
                if (jedis == null) {
                    jedis.close();
                }
            }
            Student student = stuentDao.QueryStudentById(id);
            if (student == null) {
                return null;
            }
            try {
                jedis = RedisUtil.getConnction();
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("name", student.getName());
                hashMap.put("age", student.getAge().toString());
                hashMap.put("gender", student.getGender());
                hashMap.put("clazz", student.getClazz());
                jedis.hmset(key, hashMap);
                jedis.expire(key, 10);

            } catch (Exception e) {
                System.out.println("写入缓存失败");
            } finally {
                if (jedis == null) {
                    jedis.close();
                }
            }
            return student;
        }
}
